package shake.filter;

import java.io.IOException;

import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

import shake.annotation.FilterComponent;
import shake.annotation.Sort;
import shake.context.ComponentRegistry;
import shake.event.EventAgent;
import shake.init.module.ComponentDescriptor;
import shake.servlet.ShakeServletContext;

import com.google.inject.Inject;
import com.google.inject.Injector;
import com.google.inject.servlet.RequestScoped;

@Sort(within = RedirectFilter.class)
@FilterComponent
public class RequestScopeFilter extends AbstractFilter {
	@Inject
	public RequestScopeFilter(Filters filters) {
		super(filters);
	}

	public void destroy() {
	}

	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		Injector injector = ShakeServletContext.getInjector();
		startup(injector, request);
		chain.doFilter(request, response);
		destroy(injector, request);
	}

	private void destroy(Injector injector, ServletRequest request) {
		ComponentRegistry reg = injector.getInstance(ComponentRegistry.class);
		EventAgent agent = injector.getInstance(EventAgent.class);
		for (ComponentDescriptor desc : reg) {
			if (RequestScoped.class.equals(desc.getScopeAnnotation())) {
				Object obj = request.getAttribute(desc.getKey().toString());
				if (obj != null) {
					agent.getDestory().fireEvent(obj);
				}
			}
		}
	}

	private void startup(Injector injector, ServletRequest request) {
		ComponentRegistry reg = injector.getInstance(ComponentRegistry.class);
		EventAgent agent = injector.getInstance(EventAgent.class);
		for (ComponentDescriptor desc : reg) {
			if (RequestScoped.class.equals(desc.getScopeAnnotation())) {
				if (desc.isStartup()) {
					Object obj = injector.getInstance(desc.getKey());
					agent.getStartup().fireEvent(obj);
				}
			}
		}

	}

	public void init(FilterConfig filterConfig) throws ServletException {

	}

}
